package swu.cx.roomwords

import android.app.Dialog
import android.content.ClipData
import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Adapter
import android.widget.CompoundButton
import android.widget.SearchView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.properties.Delegates

class MainActivity : AppCompatActivity() {
    private lateinit var viewModel: MyViewModel
    private lateinit var filteredWords:LiveData<List<Word>>
    private lateinit var adapter1:MyAdapter
    private lateinit var adapter2:MyAdapter
    private var viewType by Delegates.notNull<Boolean>()
    private lateinit var allWords:List<Word>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        viewModel = ViewModelProvider(this,MyViewModelFactory(application)).get(MyViewModel::class.java)
        adapter1 = MyAdapter(false,viewModel)
        adapter2 = MyAdapter(true,viewModel)
        mRecycler.layoutManager = LinearLayoutManager(
            this,LinearLayoutManager.VERTICAL,false)
         viewType = SharedPreferenceUtil.getInstance(this).getData()
        if (viewType){
            mRecycler.adapter = adapter2
        }else{
            mRecycler.adapter = adapter1
        }

        ItemTouchHelper(object :ItemTouchHelper.SimpleCallback(0,(ItemTouchHelper.START or ItemTouchHelper.END)){
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val deleteWord = allWords[viewHolder.adapterPosition]
                viewModel.delete(deleteWord)
                Snackbar.make(findViewById(R.id.rootView),"删除了一个单词",Snackbar.LENGTH_SHORT)
                    .setAction("撤销"){
                        viewModel.insert(deleteWord)
                    }
                    .show()
            }
        }).attachToRecyclerView(mRecycler)
        floatAddBtn.setOnClickListener {
            WordsDialog(this,viewModel).show()
        }
        filteredWords = viewModel.allWordsLive
        filteredWords.observe(this){
            val count = adapter1.itemCount
            allWords = it
            adapter1.allWords = it
            adapter2.allWords = it
            if (count!=it.size) {
                adapter1.notifyDataSetChanged()
                adapter2.notifyDataSetChanged()
            }
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.clearData->{
                AlertDialog.Builder(this)
                    .setTitle("清空数据")
                    .setPositiveButton("确定"){ dialogInterface: DialogInterface, i: Int ->
                            viewModel.clear()
                    }
                    .setNegativeButton("取消") { dialogInterface: DialogInterface, i: Int ->

                    }
                    .create()
                    .show()
            }
            R.id.switchViewType->{
                if (viewType){
                    mRecycler.adapter = adapter1
                    viewType = false
                    SharedPreferenceUtil.getInstance(this).saveData(false)
                }else{
                    mRecycler.adapter = adapter2
                    viewType = true
                    SharedPreferenceUtil.getInstance(this).saveData(true)
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu,menu)
        val searchView = menu?.findItem(R.id.app_bar_search)?.actionView as SearchView
        searchView.maxWidth = 585
        searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(p0: String?): Boolean {
                    return false
            }

            override fun onQueryTextChange(p0: String?): Boolean {
                val pattern = p0?.trim()
                filteredWords.removeObservers(this@MainActivity)
                viewModel.viewModelScope.launch {
                    filteredWords = withContext(Dispatchers.IO){
                        viewModel.findWordWithPattern(pattern!!)
                    }
                    filteredWords.observe(this@MainActivity){
                        val temp = adapter1.itemCount
                        adapter1.allWords = it
                        adapter2.allWords = it
                        allWords = it
                        if (temp!=it.size) {
                            adapter1.notifyDataSetChanged()
                            adapter2.notifyDataSetChanged()
                        }
                    }
                }
                return true

            }

        })
        return super.onCreateOptionsMenu(menu)
    }
}